import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_fun_zjversion/config/router_config.dart';
import 'package:flutter_fun_zjversion/generated/i18n.dart';
import 'package:flutter_fun_zjversion/model/article.dart';
import 'package:flutter_fun_zjversion/provider/provider_widget.dart';
import 'package:flutter_fun_zjversion/provider/view_state_widget.dart';
import 'package:flutter_fun_zjversion/ui/helper/refreh_helper.dart';
import 'package:flutter_fun_zjversion/ui/page/search/search_delegate.dart';
import 'package:flutter_fun_zjversion/ui/widget/animated_provider.dart';
import 'package:flutter_fun_zjversion/ui/widget/article_list_item.dart';
import 'package:flutter_fun_zjversion/ui/widget/banner_image.dart';
import 'package:flutter_fun_zjversion/view_model/home_model.dart';
import 'package:flutter_fun_zjversion/view_model/scroll_controller_model.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

const double kHomeRefreshHeight = 180.0;

class HomePage extends StatefulWidget {
  @override
  HomePageState createState() => new HomePageState();
}

class HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    double bannerHeight = 150 + MediaQuery.of(context).padding.top;
    return ProviderWidget2<HomeModel, TapToTopModel>(
      model1: HomeModel(),
      model2: TapToTopModel(PrimaryScrollController.of(context),
          height: bannerHeight - kToolbarHeight),
      onModelReady: (homeModel, topModel) {
        homeModel.initData();
        topModel.init();
      },
      builder: (context, homeModel, tap2TopModel, child) {
        return Scaffold(
          body: MediaQuery.removePadding(
              context: context,
              removeTop: false,
              child: Builder(builder: (_) {
                if (homeModel.error) {
                  return ViewStateWidget(onPressed: homeModel.initData());
                }
                return RefreshConfiguration.copyAncestor(
                    context: context,
                    twiceTriggerDistance: kHomeRefreshHeight - 15,
                    maxOverScrollExtent: kHomeRefreshHeight,
                    child: SmartRefresher(
                      enableTwoLevel: true,
                      controller: homeModel.refreshController,
                      header: HomeRefreshHeader(),
                      footer: RefresherFooter(),
                      onTwoLevel: () async {
                        await Navigator.of(context)
                            .pushNamed(RouteName.homeSecondFloor);
                        await Future.delayed(Duration(milliseconds: 300));
                        Provider.of<HomeModel>(context)
                            .refreshController
                            .twoLevelComplete();
                      },
                      onRefresh: homeModel.refresh,
                      onLoading: homeModel.loadMore,
                      enablePullUp: homeModel.list.isNotEmpty,
                      child: CustomScrollView(
                        controller: tap2TopModel.scrollController,
                        slivers: <Widget>[
                          SliverToBoxAdapter(),
                          SliverAppBar(
                            actions: <Widget>[
                              EmptyAnimatedSwitcher(
                                display: tap2TopModel.showTopBtn,
                                child: IconButton(
                                  icon: Icon(Icons.search),
                                  onPressed: () {
                                    showSearch(
                                        context: context,
                                        delegate: DefaultSearchDelegate());
                                  },
                                ),
                              ),
                            ],
                            flexibleSpace: FlexibleSpaceBar(
                              background: BannerWidget(),
                              centerTitle: true,
                              title: GestureDetector(
                                onDoubleTap: tap2TopModel.scrollToTop(),
                                child: EmptyAnimatedSwitcher(
                                    display: tap2TopModel.showTopBtn,
                                    child: Text(Platform.isIOS
                                        ? 'FunFlutter'
                                        : S.of(context).appName)),
                              ),
                            ),
                            expandedHeight: bannerHeight,
                            pinned: true,
                          ),
                          if(homeModel.idle)
                            HomeTopArticleList()

                        ],
                      ),
                    ));
              })),
          floatingActionButton: ScaleAnimatedSwitcher(
            child: tap2TopModel.showTopBtn &&
                    homeModel.refreshController.headerStatus !=
                        RefreshStatus.twoLevelOpening
                ? FloatingActionButton(
                    heroTag: 'homeEmpty',
                    key: ValueKey(Icons.vertical_align_top),
                    onPressed: () {
                      tap2TopModel.scrollToTop();
                    },
                    child: Icon(
                      Icons.vertical_align_top,
                    ),
                  )
                : FloatingActionButton(
                    heroTag: 'homeFab',
                    key: ValueKey(Icons.search),
                    onPressed: () {
                      showSearch(
                          context: context, delegate: DefaultSearchDelegate());
                    },
                    child: Icon(
                      Icons.search,
                    ),
                  ),
          ),
        );
      },
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  bool get wantKeepAlive => true;
}

class BannerWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 150 + MediaQuery.of(context).padding.top,
      decoration:
          BoxDecoration(color: Theme.of(context).scaffoldBackgroundColor),
      child: Consumer<HomeModel>(builder: (_, homeModel, __) {
        if (homeModel.busy) {
          return CupertinoActivityIndicator();
        } else {
          var banners = homeModel.banner ?? [];
          return Swiper(
            loop: true,
            autoplay: true,
            autoplayDelay: 5000,
            pagination: SwiperPagination(),
            itemCount: banners.length,
            itemBuilder: (ctx, index) {
              return InkWell(
                onTap: () {
                  print("顶部banner点击事件");
                },
                child: BannerImage(banners[index].imagePath),
              );
            },
          );
        }
      }),
    );
  }
}
class HomeTopArticleList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    HomeModel homeModel = Provider.of(context);
    return SliverList(
        delegate: SliverChildBuilderDelegate(
            (context,index){
              Article item = homeModel.topArticles[index];
              return ArticleItemWidget(
                article: item,
                index: index,
                top: true,
                hideFavourite: false,
              );
            },
          childCount: homeModel.topArticles?.length ?? 0,
        ),

    );
  }
}